package com.ocom.ugcapi.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.card.EntityXfMerchPayInfo;
import com.ocom.common.entity.card.EntityXfSignNo;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.payconfig.EntitySignatureRecord;
import com.ocom.common.entity.payconfig.EntityXfSignOrder;
import com.ocom.common.entity.typehandler.SignNoHandle;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.SignatureListRequest;
import com.ocom.common.request.payconfig.SignatureUpdateRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.common.vo.ugcapi.SignListVo;
import com.ocom.common.vo.webapi.PageVO;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.CompanyClientService;
import com.ocom.ugcapi.client.HumanClientService;
import com.ocom.ugcapi.client.PayConfigClientService;
import com.ocom.ugcapi.service.PayService;
import com.ocom.ugcapi.util.Sm2Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/7/18
 **/
@RefreshScope
@Slf4j
@RestController
public class SignController {


	@Autowired
	PayConfigClientService payConfigClientService;

	@Resource
	private RedisUtil redisUtil;

	@Autowired
	private PayService payService;

	@Autowired
	CompanyClientService companyClientService;

	@Autowired
	HumanClientService humanClientService;

//	@Value("${paycenter.url}")
//	String url;

	/**
	 * 获取代扣列表
	 * @param map
	 * @return
	 */
	@Deprecated
	//	@PostMapping(WxServiceUrl.URL_signList)
	public Result signList(@RequestBody Map<String,Object> map){
		GzhUserInfo userInfo = (GzhUserInfo)map.get("userInfo");
		Result result2 = payConfigClientService.signList(userInfo.getComId(),0);
		Map<String , Object> map1 =new HashMap<>();
		map1.put("list",result2.getData());
		map1.put("type",userInfo.getSignType());
		return ResultUtil.success(map1);
	}

	/**
	 * 簽約
	 *
	 * @param map
	 * @return
	 */
	@PostMapping(WxServiceUrl.URL_sign)
	public Result sign(@RequestBody Map<String, Object> map) throws Exception {
		log.info("签约解约参数  xBuE12u0  map 【{}】",map);

		//签约类型
		Integer payWay = (Integer) map.get("payWay");
		Integer merchId = (Integer) map.get("merchId");
		GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");

		//1 签约  2解约
		Integer signType = (Integer) map.get("signType");
		if(signType==null){
			signType=1;
		}

		if(map.get("phone")!=null){
			String pPhone = (String) map.get("phone");
			if(pPhone.length()==11){
				userInfo.setPPhone(pPhone);
			}
		}


		if(payWay!=37 && signType == 1 && CommonUtil.isNull(userInfo.getPPhone())){
			return  ResultUtil.error(ResultEnum.Err_3059);
		}

		Result result54 = payConfigClientService.getUserPayWay(userInfo.getComId(),userInfo.getPId(),merchId,payWay);

		//勿重复签约
		if(signType==1){
			if(result54.getCode()==200){
				return  ResultUtil.error(ResultEnum.Err_3052);
			}
		}

		//解约
		String signNo = "";
		if(signType==2 && payWay!=30){
			if(result54.getCode()!=200){
				return  ResultUtil.error(ResultEnum.Err_3060);
			}
			EntityXfSignNo entityXfSignNo = JSON.parseObject(JSON.toJSONString(result54.getData()),EntityXfSignNo.class);
			SignNoHandle signNoHandle =new SignNoHandle();
			signNo = signNoHandle.decrypt(entityXfSignNo.getSignNo(),1l);
		}

		Result result1 = payConfigClientService.MerchPageInfo(userInfo.getComId(), merchId);

		if (result1.getCode() != 200) {
			return ResultUtil.error(ResultEnum.Err_3045);
		}
//		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result1.getData()));

		//雪花Id
		Integer workId = (Integer) redisUtil.hmGet("Snowflake:workerId:process", IPUtils.getLocalPort());
		if (workId == null) {
			Long nowWorkId = redisUtil.incr("Snowflake:workerId:process:incr", 1l);
			if (nowWorkId > 28) {
				redisUtil.del("Snowflake:workerId:process:incr");
				redisUtil.del("Snowflake:workerId:process");
				nowWorkId = redisUtil.incr("Snowflake:workerId:process:incr", 1l);
			}
			workId = nowWorkId.intValue();
			redisUtil.hmSet("Snowflake:workerId:process", IPUtils.getLocalPort(), workId);
		}
		SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(workId, 5, workId);

		String ord = Long.toString(snowflakeIdWorker.nextId());
		ord = userInfo.getComId() + "A" + merchId + "A" + ord;

		//签约单记录
		EntityXfSignOrder entityXfSignOrder = new EntityXfSignOrder();
		entityXfSignOrder.setComId(userInfo.getComId());
		entityXfSignOrder.setMerchId(merchId);
		entityXfSignOrder.setPId(userInfo.getPId());
		entityXfSignOrder.setOrderNo(ord);
		entityXfSignOrder.setBank(userInfo.getPPhone());

//		if (payWay == 37 && signType == 1) {
//			//姓名
//			String uName = (String) map.get("userName");
//			String IdCrdNo = (String) map.get("idCrdNo");
//			entityXfSignOrder.setBank(uName + "#" + userInfo.getPPhone() + "#" + IdCrdNo);
//		}

		entityXfSignOrder.setSignType(signType);
		entityXfSignOrder.setPayWay(payWay);
		entityXfSignOrder.setSignNo("");
		Result result = payConfigClientService.addPaySign(entityXfSignOrder);

		log.info("调用签约返回 【{}】",result);
		if (result.getCode() != 200) {
			return ResultUtil.error(ResultEnum.Err_3051);
		}

//		redisUtil.set("SignOrder:"+ord ,gson.toJson(userInfo),3600l);

		//添加申请记录

		if (payWay == 7 && signType == 1) {

			/**
			 * {
			 * 	"company_id":"20210605001",
			 *     "user_name":"BusTest",
			 *     "password":"123456",
			 *     "phone": "183695885",
			 *     "out_trade_no": "183695885",
			 *     "interface_notify": "183695885"
			 *
			 * }
			 */

//		stringObjectMap.put("company_id",jsonObject.getString("companyId"));
//		stringObjectMap.put("user_name",jsonObject.getString("userName"));
//		stringObjectMap.put("password",jsonObject.getString("password"));


			EntityXfMerchPayInfo entityXfMerchPayInfo= new EntityXfMerchPayInfo();
			entityXfMerchPayInfo.setComId(userInfo.getComId());
			entityXfMerchPayInfo.setMerchId(merchId);
			Result result3 = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
			log.info("签约商户信息，【{}】",result3);
			if(result3.getCode()!=200){
				return ResultUtil.error(ResultEnum.Err_3053);
			}

			EntityXfMerchPayInfo entityXfMerchPayInfo1 = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityXfMerchPayInfo.class);
			Map<String, Object> stringObjectMap = new HashMap<>();

			stringObjectMap.put("company_id", entityXfMerchPayInfo1.getCompanyId());
			stringObjectMap.put("user_name", entityXfMerchPayInfo1.getUserName());
			stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
			stringObjectMap.put("phone", userInfo.getPPhone());
			stringObjectMap.put("out_trade_no", ord);
			stringObjectMap.put("interface_notify", "http://gzh.ocom30.com/sign");

			RequestUtil requestUtil = new RequestUtil();


			String url = payService.getPayCenterUrl(userInfo.getComId(),entityXfMerchPayInfo1.getCompanyId());
			String RealUrl = url + "ccbb/withholding.do";

			System.out.println(RealUrl);
			System.out.println(stringObjectMap);

			log.info("申请签约 地址，【{}】",RealUrl);
			log.info("申请签约 参数，【{}】",stringObjectMap);

			Map<String, String> re  = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));
			log.info("申请签约 参数 【】 返回 【】", stringObjectMap, re);
			log.info("参数 【】 ", stringObjectMap);

			Result result2 = JSON.parseObject(JSON.toJSONString(re), Result.class);
			return result2;
		}

		if (payWay == 7 && signType == 2) {


			EntityXfMerchPayInfo entityXfMerchPayInfo= new EntityXfMerchPayInfo();
			entityXfMerchPayInfo.setComId(userInfo.getComId());
			entityXfMerchPayInfo.setMerchId(merchId);
			Result result3 = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
			log.info("签约商户信息，【{}】",result3);
			if(result3.getCode()!=200){
				return ResultUtil.error(ResultEnum.Err_3053);
			}

			EntityXfMerchPayInfo entityXfMerchPayInfo1 = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityXfMerchPayInfo.class);
			Map<String, Object> stringObjectMap = new HashMap<>();

			stringObjectMap.put("company_id", entityXfMerchPayInfo1.getCompanyId());
			stringObjectMap.put("user_name", entityXfMerchPayInfo1.getUserName());
			stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
			stringObjectMap.put("contract_id", signNo);

			RequestUtil requestUtil = new RequestUtil();
//			System.out.println(RealUrl);
//			System.out.println(stringObjectMap);
			String url = payService.getPayCenterUrl(userInfo.getComId(),entityXfMerchPayInfo1.getCompanyId());
			String RealUrl = url + "ccbb/rescind.do";

			log.info("申请解约 地址，【{}】",RealUrl);
			log.info("申请解约 参数，【{}】",stringObjectMap);

			Map<String, String> re  = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));
			log.info("申请解约 参数 【】 返回 【】", stringObjectMap, re);
			log.info("参数 【】 ", stringObjectMap);

			Result result2 = JSON.parseObject(JSON.toJSONString(re), Result.class);

//			boolean ex = result2.getMsg().contains("商户信息不正确");

			//成功
			if(result2.getCode()==200 ){
				entityXfSignOrder.setStatus(2);
				payConfigClientService.updatePaySign(entityXfSignOrder);
			}
//			if(ex){
//				result2.setCode(200);
//				result2.setMsg("解约成功");
//			}

			return result2;
		}
		/**
		 *  建行签约示例
		 * {
		 * 	"code": 200,
		 * 	"msg": "success",
		 * 	"data": {
		 * 		"code_url": "http://124.127.94.54:22811/CCBIS/B2CMainPlat_00_PD_BEPAY?CCB_IBSVersion=V6&MERCHANTID=105000053996456&POSID=313336473&BRANCHID=460000000&ccbParam=RuCEuB19EDInGoqkKQ%2FtxNj6kGUpjzRK1FJV3xmhaR5nRCmixi9gGKu%2CAEtbSFHK3BlekICsV5c9F8%2CJkzUnvhb5iCOvDD6nugLPo8fbHgtQYrGXkoHgr5dF6LHak%2FndAO9bTbgNjOJ%2Fjl8KaX7DZuy3b%2F25k7M2vYtD2JSHcRmMnABiQWbQ8YhSXy%2FyCvG1I9OPduXdP4mZbo5ar8Lw%2F0rG20CUbkOkqeGKP9F9Y0CHb2wiZC8h0B6AZM2tLsoNvWUoRmVSrc8XuH3qzOWCoXXlqQubGb17Bi8fXBsHuUXdx%2CemvNSC8wn7Qw%2CmPCfrsLDvZ8i%2FYfg8djIGUZ2xLLZDqAC6WDuHDKQak5JzCTodE4dcgDdAO4XAeo086JLbtpit5NnToGJyf%2CYLxDNL1gafRw6xbeicmPqMWddhxAbBBkgtQu6FM0c6oT1iQdswuRXfTVfA0nj0Sx%2C2P5Xo8V316fHtOlMg1gG1MsNchjH0X6iCPG8H%2CnFLFLhZnB3%2CBWE3ZFhdYmGjnQuGDuF2xOdZ%2FOw0%2FX9qy4bJKgYVDLA%2Cm5M1WJhjYzt8uWyBTJM6%2CziQ4Ewj%2Cus%3D"
		 *        }
		 * }
		 */


		if (payWay == 30) {

			EntityXfMerchPayInfo entityXfMerchPayInfo= new EntityXfMerchPayInfo();
			entityXfMerchPayInfo.setComId(userInfo.getComId());
			entityXfMerchPayInfo.setMerchId(merchId);
			Result result3 = payConfigClientService.getPayInfo(entityXfMerchPayInfo);
			log.info("签约商户信息，【{}】",result3);
			if(result3.getCode()!=200){
				return ResultUtil.error(ResultEnum.Err_3053);
			}

			EntityXfMerchPayInfo entityXfMerchPayInfo1 = JSON.parseObject(JSON.toJSONString(result3.getData()),EntityXfMerchPayInfo.class);
			Map<String, Object> stringObjectMap = new HashMap<>();

			stringObjectMap.put("companyId", entityXfMerchPayInfo1.getCompanyId());
			stringObjectMap.put("userName", entityXfMerchPayInfo1.getUserName());
			stringObjectMap.put("password", entityXfMerchPayInfo1.getPassword());
			stringObjectMap.put("payTime", DateUtil.getDateTime());
			stringObjectMap.put("type", signType);
			String userSignNo = MD5.MD5Encode(userInfo.getOpenId(),"utf8");
			stringObjectMap.put("signNo", userSignNo);

			String url = payService.getPayCenterUrl(userInfo.getComId(),entityXfMerchPayInfo1.getCompanyId());
			String RealUrl = url + "cmbywt/sign.do";

			RequestUtil requestUtil = new RequestUtil();
			System.out.println(RealUrl);
			System.out.println(stringObjectMap);

			log.info("申请签约 地址，【{}】",RealUrl);
			log.info("申请签约 参数，【{}】",stringObjectMap);

			Map<String, String> re  = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));
			log.info("招行一网通申请解约 参数 【】 返回 【】", stringObjectMap, re);
			log.info("参数 【】 ", stringObjectMap);

			Result result2 = JSON.parseObject(JSON.toJSONString(re), Result.class);
			return result2;
		}


		/**
		 * //测试
		 * http://etest.lzbank.com:20016/ares-mobile-gateway/mbankPage7.0/online/1000/5/01000000/page/index.html#page/11/1119/P1119.html?CHNL_ID=1000
		 * //试运行地址
		 * http://ebank.lzbank.com:9001/ares-mobile-gateway7.0/online/1000/5/01000000/page/index.html#page/11/1119/P1119.html?CHNL_ID=1000
		 * //生产地址
		 * https://ebank.lzbank.com:9005/ares-mobile-gateway7.0/online/1000/5/01000000/page/index.html#page/11/1119/P1119.html?CHNL_ID=1000
		 */

		/**
		 * IdCrdNo	用户身份证号	String(18)	是
		 * Name	用户姓名
		 * 	String(64)	是
		 * IdentTp	用户证件类型	String(4)	是
		 * CtcTel	用户联系电话	String(11)	是
		 * SchoolNm	学校名称	String(64)	是
		 */




		//兰州银行签约
		if (payWay == 37 && signType == 1){

			Result<EntityWechatAppInfo> wxInfo = payConfigClientService.getWxInfo(userInfo.getComId(),merchId.longValue());
			if(wxInfo.getCode()!=200){
				return wxInfo;
			}

//			//手机号
//			String base64Phone = Sm2Utils.getSm2Encry(userInfo.getPPhone() ,wxInfo.getData().getAlipayPublicKey());
//
//			//姓名
//			String uName  = (String) map.get("userName");
//			String base64Name = Sm2Utils.getSm2Encry(uName ,wxInfo.getData().getAlipayPublicKey());
//
//			//身份证
//			String IdCrdNo  = (String) map.get("idCrdNo");
//			String base64IdCrdNo = Sm2Utils.getSm2Encry(IdCrdNo ,wxInfo.getData().getAlipayPublicKey());

			//学校名
			String base64SchoolName = Sm2Utils.getSm2Encry(wxInfo.getData().getAlipayAes() ,wxInfo.getData().getAlipayPublicKey());

			//身份类型
			String base64IdentTp = Sm2Utils.getSm2Encry("01" ,wxInfo.getData().getAlipayPublicKey());

			//返回地址
			String base64Callback = Sm2Utils.getSm2Encry("http://gzh.ocom30.com/signResult",wxInfo.getData().getAlipayPublicKey());

			//签约单号
			String signOrderNo = Sm2Utils.getSm2Encry(ord ,wxInfo.getData().getAlipayPublicKey());

			//signFlag，1是签约   2是解约
			String signFlag = Sm2Utils.getSm2Encry("1" ,wxInfo.getData().getAlipayPublicKey());


			Result<XfUserInfoVo> userInfoVoResult = humanClientService.getXfUserInfo(userInfo.getComId(),userInfo.getPId());
			String studentName = userInfo.getPId().toString();
			String pCode = userInfo.getPId().toString();
			if(userInfoVoResult.getCode()==200){
				studentName = userInfoVoResult.getData().getPName();
				pCode = userInfoVoResult.getData().getPCode();
			}

			studentName = Sm2Utils.getSm2Encry( studentName ,wxInfo.getData().getAlipayPublicKey());
			pCode = Sm2Utils.getSm2Encry( pCode ,wxInfo.getData().getAlipayPublicKey());


			String codeUrl = "https://ebank.lzbank.com:9005/ares-mobile-gateway7.0/online/1000/5/11000000/page/client.html#page/11/1119/P1119.html?CHNL_ID=1000"  + "&SchoolNm="+base64SchoolName+ "&callback="+ base64Callback + "&signOrderNo="+signOrderNo +"&signFlag="+signFlag+"&studentName="+ studentName +"&IdNo="+ pCode;

			//+ "&IdCrdNo="+ base64IdCrdNo +"&Name="+ base64Name + "&IdentTp=" +base64IdentTp+"&CtcTel="+ base64Phone


			return ResultUtil.success(codeUrl);
		}


		//兰州银行解约
		if (payWay == 37 && signType == 2){
//			EntityXfSignNo entityXfSignNo =new EntityXfSignNo();
//			entityXfSignNo.setComId(userInfo.getComId());
//			entityXfSignNo.setMerchId(0);
//			entityXfSignNo.setPId(userInfo.getPId());
//			entityXfSignNo.setPayWay(37);
//			return payConfigClientService.delUserSign(entityXfSignNo);
			Result<EntityWechatAppInfo> wxInfo = payConfigClientService.getWxInfo(userInfo.getComId(),merchId.longValue());
			if(wxInfo.getCode()!=200){
				return wxInfo;
			}

			Result<EntityXfSignNo> signNoResult = payConfigClientService.getUserSignInfo(userInfo.getComId(),userInfo.getPId(),merchId,37,1);

			if(signNoResult.getCode()!=200){
				return signNoResult;
			}

			SignNoHandle signNoHandle = new SignNoHandle();
			String signNoStr = signNoHandle.decrypt(signNoResult.getData().getSignNo(),1l);

			String[] args = signNoStr.split("#");

			//1姓名 #  2手机号 # 3身份证 # 4签约号

			//签约号
			String base64SignNo = Sm2Utils.getSm2Encry(args[3],wxInfo.getData().getAlipayPublicKey());

			//手机号
//			String base64Phone = Sm2Utils.getSm2Encry(args[1],wxInfo.getData().getAlipayPublicKey());

			//学校名
			String base64SchoolName = Sm2Utils.getSm2Encry(wxInfo.getData().getAlipayAes() ,wxInfo.getData().getAlipayPublicKey());

			//身份类型
			String base64IdentTp = Sm2Utils.getSm2Encry("01" ,wxInfo.getData().getAlipayPublicKey());

			//返回地址
			String base64Callback = Sm2Utils.getSm2Encry("http://gzh.ocom30.com/signResult",wxInfo.getData().getAlipayPublicKey());

			//签约单号
			String signOrderNo = Sm2Utils.getSm2Encry(ord ,wxInfo.getData().getAlipayPublicKey());

			//signFlag，1是签约   2是解约
			String signFlag = Sm2Utils.getSm2Encry("2" ,wxInfo.getData().getAlipayPublicKey());

			Result<XfUserInfoVo> userInfoVoResult = humanClientService.getXfUserInfo(userInfo.getComId(),userInfo.getPId());
			String pCode = userInfo.getPId().toString();
			String studentName = userInfo.getPId().toString();
			if(userInfoVoResult.getCode()==200){
				studentName = userInfoVoResult.getData().getPName();
				pCode = userInfoVoResult.getData().getPCode();
			}

			studentName = Sm2Utils.getSm2Encry( studentName ,wxInfo.getData().getAlipayPublicKey());
			pCode = Sm2Utils.getSm2Encry( pCode ,wxInfo.getData().getAlipayPublicKey());


			String codeUrl = "https://ebank.lzbank.com:9005/ares-mobile-gateway7.0/online/1000/5/11000000/page/client.html#page/11/1119/P1119.html?CHNL_ID=1000" + "&OrdrNo="+ base64SignNo + "&IdentTp=" +base64IdentTp + "&SchoolNm="+base64SchoolName+ "&callback="+ base64Callback + "&signOrderNo="+signOrderNo +"&signFlag="+signFlag +"&studentName="+ studentName  +"&IdNo="+ pCode;

			// +"&CtcTel="+ base64Phone

			if(args.length>=5){
				String cardNo = args[4];
				cardNo = Sm2Utils.getSm2Encry( cardNo ,wxInfo.getData().getAlipayPublicKey());
				codeUrl = codeUrl+"&cardNo=" + cardNo;
			}
			
			return ResultUtil.success(codeUrl);
		}

		return ResultUtil.success();
	}

//	//建行签约回调
//	//https://mj.ocomtraffic.com/ugcapi/JHcallback
//	@PostMapping(WxServiceUrl.URL_JHcallback)
//	public Result JHcallback(@RequestBody Map<String,Object> map) {
//		log.info("收到建行签约回调， map 【{}】",map);
//		JHcallbackVo jHcallbackVo = JSON.parseObject(JSON.toJSONString(map),JHcallbackVo.class);
//		log.info("收到建行签约回调，【{}】",jHcallbackVo);
//		if (jHcallbackVo.getCode() == 200 && jHcallbackVo.getData().getResult().equals("success")) {
//			//处理签约  解约  回调
//			Result result = payConfigClientService.getPaySign(jHcallbackVo.getData().getOut_trade_no());
//			if (result.getCode() == 200) {
//				EntityXfSignOrder entityXfSignOrder = JSON.parseObject(JSON.toJSONString(result.getData()), EntityXfSignOrder.class);
//				if (jHcallbackVo.getData().getNotificationType().equals("signing")) {
//					entityXfSignOrder.setStatus(2);
//				}
//				if (jHcallbackVo.getData().getNotificationType().equals("rescind")) {
//					entityXfSignOrder.setStatus(3);
//				}
////				signing-签约通知
////				rescind-解约通知
////				pre_order-预下单
//				entityXfSignOrder.setSignNo(jHcallbackVo.getData().getContract_id());
//				payConfigClientService.updatePaySign(entityXfSignOrder);
//			}
//		}
//		return ResultUtil.success();
//	}


	//获取一跳代扣信息
	@PostMapping(PayConfigUrl.Url_getUserSign)
	public Result getUserSign(@RequestBody Map<String, Object> map) {
		GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");
		return payConfigClientService.getUserSign(userInfo.getComId(), userInfo.getPId());
	}

//	@GetMapping("/test98")
//	public Result  lk(){
//		//雪花Id
//		String rnad = RandomUtil.getRandomString(10);
//		Integer workId=(Integer)redisUtil.hmGet("Snowflake:workerId:process", rnad);
//		if(workId==null ){
//			Long nowWorkId=redisUtil.incr("Snowflake:workerId:process:incr",1l);
//			if(nowWorkId>28){
//				redisUtil.del("Snowflake:workerId:process:incr");
//				redisUtil.del("Snowflake:workerId:process");
//				nowWorkId=redisUtil.incr("Snowflake:workerId:process:incr",1l);
//			}
//			workId=nowWorkId.intValue();
//			redisUtil.hmSet("Snowflake:workerId:process",rnad,workId);
//		}
//		SnowflakeIdWorker snowflakeIdWorker=  new SnowflakeIdWorker(workId,5,workId);
//		return ResultUtil.success(snowflakeIdWorker);
//	}

	@GetMapping("/test98")
	public Map  lk(){
		Map<String, Object> stringObjectMap = new HashMap<>();
//			stringObjectMap.put("company_id", "20220722001");
//			stringObjectMap.put("user_name", "JianHangENYDaiKou");
//			stringObjectMap.put("password", "123456");
		stringObjectMap.put("company_id", "20220804001");
		stringObjectMap.put("user_name", "JianHanDaiKou");
		stringObjectMap.put("password", "123456");
		stringObjectMap.put("phone", "15812902593");
		stringObjectMap.put("out_trade_no", "158129025933333");
		stringObjectMap.put("interface_notify", "http://gzh.ocom30.com");
		RequestUtil requestUtil = new RequestUtil();
		Map<String, String> re  = requestUtil.doPostJson("http://192.168.3.123:32880/ocom_pay/ccbb/withholding.do", JSON.toJSONString(stringObjectMap));
		log.info("申请签约 参数 【】 返回 【】", stringObjectMap, re);
		return re;
	}



	@Autowired
	private HttpServletRequest request;

	//插入一条授权 -- 协议列表的签约
	@PostMapping(WxServiceUrl.URL_createSign)
	public Result createSign(@RequestBody Map<String, Object> map) {
		GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");
//		GzhUserInfo userInfo = new GzhUserInfo();
//		userInfo.setComId(52l);
//		userInfo.setPId(525l);


		Map<String, String> stringMap = getHeadersInfo() ;

		EntitySignatureRecord entitySignatureRecord=new EntitySignatureRecord();
		entitySignatureRecord.setComId(userInfo.getComId());
		entitySignatureRecord.setPId(userInfo.getPId());
		entitySignatureRecord.setSignatureImageUrl(map.get("signatureImageUrl").toString());
		entitySignatureRecord.setIpAddress(stringMap.get("remoteip"));


		log.info("获取到header tlTSwYL9 【{}】",stringMap);

		String userAgent = stringMap.get("user-agent");
		if(userAgent.length()>250) userAgent =userAgent.substring(0,250);
		entitySignatureRecord.setUserAgent(userAgent);
		entitySignatureRecord.setType((Integer) map.get("type"));

		return payConfigClientService.addSignRecords(entitySignatureRecord);
	}

	//撤销一条授权
	@PostMapping(WxServiceUrl.URL_revokedSign)
	public Result revokedSign(@RequestBody Map<String, Object> map) {
		GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");

//		GzhUserInfo userInfo = new GzhUserInfo();
//		userInfo.setComId(52l);
//		userInfo.setPId(525l);

		SignatureUpdateRequest signatureUpdateRequest=new SignatureUpdateRequest();
		signatureUpdateRequest.setComId(userInfo.getComId());
		signatureUpdateRequest.setPId(userInfo.getPId());
		signatureUpdateRequest.setType((Integer) map.get("type"));

		return payConfigClientService.revokedSignRecords(signatureUpdateRequest);
	}


	//查看签约
	@PostMapping(WxServiceUrl.URL_gzhSignList)
	public Result gzhSignList(@RequestBody Map<String, Object> map) {
		GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");

//		GzhUserInfo userInfo = new GzhUserInfo();
//		userInfo.setComId(52l);
//		userInfo.setPId(525l);

		Result<List<EntityCompanyConfig>> result3 = companyClientService.getCompanyConfig(userInfo.getComId(),"gzhSignList");
		log.info("读取到配置 【{}】",result3);
		if(result3.getData() !=null && result3.getData().size()>0 ){
			List<SignListVo> listVos = JSON.parseArray(result3.getData().get(0).getConfig(),SignListVo.class);

			SignatureListRequest signatureUpdateRequest =new SignatureListRequest();
			signatureUpdateRequest.setComId(userInfo.getComId());
			signatureUpdateRequest.setPId(userInfo.getPId());
			signatureUpdateRequest.setStatus(1);

			Result<PageVO<EntitySignatureRecord>> listResult = payConfigClientService.gzhSignRecords(signatureUpdateRequest);

			if(listResult.getCode()==200 && listResult.getData().getTotal()>0){
				List<Integer> types = listResult.getData().getList().stream().map(EntitySignatureRecord::getType).collect(Collectors.toList());
				for (SignListVo signListVo:listVos){
					if(types.contains(signListVo.getType())){
						signListVo.setStatus(1);
					}
				}
			}

			return ResultUtil.success(listVos);
		}
		return ResultUtil.error(ResultEnum.Err_1001);
	}


	//get request headers
	private Map<String, String> getHeadersInfo() {
		Map<String, String> map = new HashMap<String, String>();
		Enumeration headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()) {
			String key = (String) headerNames.nextElement();
			String value = request.getHeader(key);
			map.put(key, value);
		}
		return map;
	}



//	//兰州银行  前端接收签约解约
//	@PostMapping(WxServiceUrl.URL_signCallback)
//	public Result signCallback(@RequestBody Map<String,Object> map) {
//		log.info("收到签约回调， map 【{}】",map);
//		SignCallbackVo signCallbackVo = JSON.parseObject(JSON.toJSONString(map),SignCallbackVo.class);
//		log.info("收到建行签约回调，【{}】",signCallbackVo);
//
//		if(!signCallbackVo.getResult().equals("success")){
//			return ResultUtil.success();
//		}
//
//		//处理签约  解约  回调
//		Result<EntityXfSignOrder> result = payConfigClientService.getPaySign(signCallbackVo.getSignOrderNo());
//		if (result.getCode() == 200) {
//			EntityXfSignOrder entityXfSignOrder = result.getData();
//			entityXfSignOrder.setStatus(2);
////				signing-签约通知
////				rescind-解约通知
////				pre_order-预下单
//			if(entityXfSignOrder.getSignType()==1){
//				entityXfSignOrder.setSignNo(entityXfSignOrder.getBank()+"#"+signCallbackVo.getOrdrNo());
//			}
//			payConfigClientService.updatePaySign(entityXfSignOrder);
//
//			if(entityXfSignOrder.getSignType()==1){
//				return ResultUtil.info(200,"签约成功");
//			}else{
//				return ResultUtil.info(200,"解约成功");
//			}
//		}
//
//		return ResultUtil.success();
//	}



}
